package com.lk.socket.config;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


@ServerEndpoint(value = "/websocket/test1/{sid}")
@Component
public class MyWebsocketTest2 {

    Logger logger = LoggerFactory.getLogger(MyWebsocketTest2.class);

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    public void sendMessageAll(String message) {
    	for (Map.Entry<String, Session> entry : sessionPools.entrySet()) {
//            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
            try {
				sendMessage(entry.getValue(), message);
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
    }

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                logger.debug("remote:" + message);
                session.getBasicRemote().sendText(message);
            }
        }else {
            logger.debug("remote: fail[无session]");
        }
    }
    //给指定用户发送信息
    public void sendInfo(String userName, String message){
        Session session = sessionPools.get(userName);
        try {
            logger.debug("正式发送给用户["+userName+"]数据[" + message + "]");
            sendMessage(session, message);
        }catch (Exception e){
            logger.debug("正式发送消息异常：", e);
            e.printStackTrace();
        }
    }
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String userName) {
        sessionPools.put(userName, session);
        logger.debug("连接成功");
//        System.out.println("连接成功");
//        System.out.println(userName);
        addOnlineCount();
        logger.debug(userName + "加入webSocket！当前人数为" + onlineNum);

        JSONObject json =new JSONObject();
        json.put("data", "server连接成功");
        sendInfo(userName, json.toString());
//        System.out.println(userName + "加入webSocket！当前人数为" + onlineNum);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam(value = "sid") String userName) {
        sessionPools.remove(userName);
        subOnlineCount();
        logger.debug(userName + "断开webSocket连接！当前人数为" + onlineNum);

        JSONObject json =new JSONObject();
        json.put("data", "client关闭连接");
        sendInfo(userName, json.toString());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
//    	message = "客户端：" + message + ",已收到";
        logger.debug(message);
        for (Session session: sessionPools.values()) {
            try {
                logger.debug("服务器收到用户["+session+"]的消息：["+message+"]");

                JSONObject fromObject = JSONObject.parseObject((message));
                if("31".equals(fromObject.getString("cmd"))){//心跳
                	JSONObject json1 =new JSONObject();
                    json1.put("devType", "8000");
                    json1.put("devid", "123");
                    json1.put("cmd", 31);
                    json1.put("data", null);
                    sendMessage(session, json1.toString());


                }else {

                    JSONObject data = fromObject.getJSONObject("data");
                    Set<String> keys = data.keySet();
                    String sendKey = "";
                    for (String key : keys) {
                       if(!"dtime".equals(key)){
                           sendKey = key;
                           break;
                       }
                    }
                    JSONObject json1 =new JSONObject();
                	JSONObject json2 =new JSONObject();
                	json1.put("devType", "8000");
                    json1.put("devid", "123");
                    json1.put("cmd", fromObject.getInteger("cmd"));
//                    json2.put("aaa",Math.random());
                    json2.put("cmdAck", 0);
                    json2.put("OK", sendKey);
                    json1.put("data", json2);
                    sendMessage(session, json1.toString());
                }
//                //TODO 根据业务需要把相关信息发送给用户
//                JSONObject json =new JSONObject();
//                json.put("data", "server接收到client的数据，内容为：" + message);
//                sendMessage(session, json.toString());

//                JSONObject json1 =new JSONObject();
//                json1.put("data", "server随机给client发送了数据：" + UUID.randomUUID().toString());

//                sendMessage(session, json1.toString());

            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.debug("发生错误");
        try {
        	JSONObject json =new JSONObject();
            json.put("data", "server发生错误");
			sendMessage(session, json.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
        error.printStackTrace();

    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }


}
